﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Core.Helpers;
using System.Web;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Content;
using MvcEngine.Core;
using MvcEngine.Core.Localization;

namespace MvcEngine.Mvc.ModelBinders
{
    public abstract class ModelBinderBase : IModelBinder
    {
        protected virtual void Validate<T>(T item, ControllerContext controllerContext, string[] excludeProperties)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            var modelState = controllerContext.Controller.ViewData.ModelState;

            foreach (var key in request.Form.AllKeys)
            {
                modelState.AddValue(key, request.Form[key]);
            }

            var brokenRules = ValidationHelper.Current.GetErrors<T>(item, excludeProperties);
            if (brokenRules.Count() > 0)
            {
                ValidationHelper.Current.UpdateModelState(brokenRules, modelState);
            }
        }

        protected virtual void Validate<T>(T item, ControllerContext controllerContext)
        {
            Validate(item, controllerContext, null);
        }

        protected virtual bool GetBool(string requestParamValue)
        {
            if (!string.IsNullOrEmpty(requestParamValue) && requestParamValue.Contains("true"))
                return true;
            return false;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Control control = null;

            if (controllerContext.RouteData.Values.ContainsKey("controlKey"))
            {
                control = ContentManager.Current.GetControlByKey(controllerContext.RouteData.Values["controlKey"] as string);
            }

            if (control != null)
            {
                Module module = ContentManager.Current.GetModule(control.ModuleId);
                controllerContext.RouteData.Values["moduleName"] = module.Name;
                controllerContext.HttpContext.Items["moduleName"] = module.Name;
                controllerContext.RouteData.Values["controlId"] = control.Id;
            }

            LocalizationUtil.SetThreadLanguage(controllerContext.HttpContext.Request);

            return Bind(controllerContext, bindingContext);
        }

        public abstract object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext);
    }
}
